import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { MembershipPackage } from './entities/membership-package.entity';
import { CreateMembershipPackageDto } from './dto/create-membership-package.dto';
import { UpdateMembershipPackageDto } from './dto/update-membership-package.dto';

/**
 * 会员套餐服务
 */
@Injectable()
export class MembershipService {
  private readonly logger = new Logger(MembershipService.name);

  constructor(
    @InjectRepository(MembershipPackage)
    private readonly membershipPackageRepository: Repository<MembershipPackage>,
  ) {}

  /**
   * 创建会员套餐
   */
  async create(createDto: CreateMembershipPackageDto): Promise<MembershipPackage> {
    this.logger.log(`创建会员套餐: ${createDto.name}`);
    const membershipPackage = this.membershipPackageRepository.create({
      ...createDto,
      level: createDto.level || 1,
      isActive: createDto.isActive !== undefined ? createDto.isActive : true,
    });
    const result = await this.membershipPackageRepository.save(membershipPackage);
    this.logger.log(`会员套餐创建成功，ID: ${result.id}`);
    return result;
  }

  /**
   * 获取所有会员套餐
   */
  async findAll(): Promise<MembershipPackage[]> {
    return await this.membershipPackageRepository.find({
      where: { isActive: true },
      order: { level: 'ASC', price: 'ASC' },
    });
  }

  /**
   * 分页获取会员套餐
   */
  async findWithPagination(page: number = 1, limit: number = 10, includeInactive: boolean = false): Promise<{
    data: MembershipPackage[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  }> {
    const where = includeInactive ? {} : { isActive: true };
    const [data, total] = await this.membershipPackageRepository.findAndCount({
      where,
      order: { level: 'ASC', price: 'ASC' },
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      data,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 获取所有会员套餐（包含禁用的）
   */
  async findAllForAdmin(): Promise<MembershipPackage[]> {
    return await this.membershipPackageRepository.find({
      order: { level: 'ASC', price: 'ASC' },
    });
  }

  /**
   * 根据ID获取会员套餐
   */
  async findOne(id: number): Promise<MembershipPackage> {
    const membershipPackage = await this.membershipPackageRepository.findOne({
      where: { id },
    });
    if (!membershipPackage) {
      throw new NotFoundException(`会员套餐 ID ${id} 不存在`);
    }
    return membershipPackage;
  }

  /**
   * 更新会员套餐
   */
  async update(id: number, updateDto: UpdateMembershipPackageDto): Promise<MembershipPackage> {
    this.logger.log(`更新会员套餐，ID: ${id}`);
    const membershipPackage = await this.findOne(id);
    Object.assign(membershipPackage, updateDto);
    const result = await this.membershipPackageRepository.save(membershipPackage);
    this.logger.log(`会员套餐更新成功，ID: ${id}`);
    return result;
  }

  /**
   * 删除会员套餐（软删除，设置为禁用）
   */
  async remove(id: number): Promise<void> {
    this.logger.log(`删除会员套餐，ID: ${id}`);
    const membershipPackage = await this.findOne(id);
    membershipPackage.isActive = false;
    await this.membershipPackageRepository.save(membershipPackage);
    this.logger.log(`会员套餐删除成功，ID: ${id}`);
  }

  /**
   * 启用会员套餐
   */
  async enable(id: number): Promise<MembershipPackage> {
    const membershipPackage = await this.findOne(id);
    membershipPackage.isActive = true;
    return await this.membershipPackageRepository.save(membershipPackage);
  }

  /**
   * 禁用会员套餐
   */
  async disable(id: number): Promise<MembershipPackage> {
    const membershipPackage = await this.findOne(id);
    membershipPackage.isActive = false;
    return await this.membershipPackageRepository.save(membershipPackage);
  }

  /**
   * 根据等级获取会员套餐
   */
  async findByLevel(level: number): Promise<MembershipPackage[]> {
    return await this.membershipPackageRepository.find({
      where: { level, isActive: true },
      order: { price: 'ASC' },
    });
  }

  /**
   * 获取推荐套餐（按价格排序，取前3个）
   */
  async findRecommended(): Promise<MembershipPackage[]> {
    return await this.membershipPackageRepository.find({
      where: { isActive: true },
      order: { price: 'ASC' },
      take: 3,
    });
  }

  /**
   * 获取套餐统计信息
   */
  async getStatistics(): Promise<{
    total: number;
    active: number;
    inactive: number;
    levels: { level: number; count: number }[];
  }> {
    const total = await this.membershipPackageRepository.count();
    const active = await this.membershipPackageRepository.count({
      where: { isActive: true },
    });
    const inactive = total - active;

    // 获取各等级套餐数量
    const levelStats = await this.membershipPackageRepository
      .createQueryBuilder('package')
      .select('package.level', 'level')
      .addSelect('COUNT(*)', 'count')
      .where('package.isActive = :isActive', { isActive: true })
      .groupBy('package.level')
      .orderBy('package.level', 'ASC')
      .getRawMany();

    const levels = levelStats.map(stat => ({
      level: parseInt(stat.level),
      count: parseInt(stat.count),
    }));

    return {
       total,
       active,
       inactive,
       levels,
     };
   }

   /**
    * 搜索会员套餐
    */
   async search(keyword: string, includeInactive: boolean = false): Promise<MembershipPackage[]> {
     const queryBuilder = this.membershipPackageRepository.createQueryBuilder('package');
     
     queryBuilder.where(
       '(package.name LIKE :keyword OR package.description LIKE :keyword)',
       { keyword: `%${keyword}%` }
     );

     if (!includeInactive) {
       queryBuilder.andWhere('package.isActive = :isActive', { isActive: true });
     }

     queryBuilder.orderBy('package.level', 'ASC').addOrderBy('package.price', 'ASC');

     return await queryBuilder.getMany();
   }

   /**
    * 批量更新套餐状态
    */
   async batchUpdateStatus(ids: number[], isActive: boolean): Promise<void> {
     await this.membershipPackageRepository.update(
       { id: In(ids) },
       { isActive }
     );
   }
 }